package org.lonetree.tc.webapp.actions;

import java.util.Iterator;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.lonetree.tc.core.Book;
import org.lonetree.tc.core.ElectronicSource;
import org.lonetree.tc.core.PhysicalSource;
import org.lonetree.tc.core.Source;
import org.lonetree.tc.core.UserSource;
import org.lonetree.tc.core.Source.SourceId;
import org.lonetree.tc.core.dao.BookDAO;
import org.lonetree.tc.core.dao.DAOFactory;
import org.lonetree.tc.core.exception.SearchException;


public class ViewSourceDetails extends SecureAction{

	@Override
	protected ActionForward executeSecure(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception{
		try{
			SourceId sid = new SourceId(request.getParameter("source_id"));
			Source s = findSource(sid);
			if(s == null)
				return mapping.findForward("failure");

			String sourcePhysicalAddress;
			String sourceElectronicAddress;
			if(s instanceof ElectronicSource){
				sourceElectronicAddress = ((ElectronicSource)s).getUrl().getUrlString();
				request.setAttribute("sourceElectronicAddress", sourceElectronicAddress);
				request.setAttribute("sourceType", "Online Retailer");
			}
			else{
				sourcePhysicalAddress = ((PhysicalSource)s).getLocation();
				request.setAttribute("sourcePhysicalAddress", sourcePhysicalAddress);
				if(s instanceof UserSource){
					request.setAttribute("sourceEmailAddress", ((UserSource)s).getUser().getEmailAddress());
					request.setAttribute("sourceType", "User");
				}
				else{
					request.setAttribute("sourceType", "Physical Retailer");
				}
			}
			
			request.setAttribute("source", s);
			request.setAttribute("userAddress", getCurrentUser().getLocation());
			return mapping.findForward("success");
		}
		catch(Exception e){
			return mapping.findForward("failure");
		}
	}

	private Source findSource(SourceId sid) throws SearchException{
		BookDAO bd = DAOFactory.getDAOFactory(DAOFactory.FactoryImplementation.DB_DAO_FACTORY).getBookDAO();
		Set<Book> books = bd.findBooks(null);
		for(Iterator<Book> itb = books.iterator(); itb.hasNext();){
			for(Iterator<Source> its = itb.next().getSources().iterator(); its.hasNext();){
				Source s = its.next();
				if(s.getSourceId().equals(sid))
					return s;
			}
		}
		
		return null;
	}

}
